<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Group;
use App\Models\User;
use App\Tool\Helper;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;


/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller
{
    // 小程序登录
    public function login(Request $request)
    {
        $code = $request->input('code');
        if (empty($code)) return $this->writeJson(500, null, '缺少code参数');

        $miniProgram = \EasyWeChat::miniProgram();
        $applt = $miniProgram->auth->session($code);
        $user = User::where(['openid' => $applt['openid']])->first();
        if (empty($user)) {
            // 用户还不存在
            return $this->writeJson(1030);
        } else {
            $token = JWTAuth::fromUser($user);
            auth('api')->login($user);
            $user = auth('api')->user();
            $login = [
                'user'         => $user,
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('api')->factory()->getTTL() * 60
            ];
            return $this->writeJson(0, $login, '登录成功，页面即将跳转...');
        }
    }

    // 注册
    public function register(Request $request)
    {
        $info = $request->post('info');
        $code = $request->post('wx_code');
        $iv = $request->post('wx_iv');
        $encryptedData = $request->post('wx_encryptedData');
        if (empty($code)) return $this->writeJson(500, null, '缺少code参数');

        $miniProgram = \EasyWeChat::miniProgram();
        $applt = $miniProgram->auth->session($code);

        $result = Helper::decryptDataWx($encryptedData, $iv, $applt['session_key']);
        if ($request) {
            $phone = $result->purePhoneNumber;

            $user = User::whereMobile($phone)->first();
            if (empty($user)) {
                // 创建
                $user = new User();
                $user->openid = $applt['openid'];
                $user->mobile = $phone;
                if ($info) {
                    $user->nickname = $info['nickName'];
                    $user->username = $info['nickName'];
                    $user->avatar = $info['avatarUrl'];
                    $user->sex = $info['gender'];
                }
                $user->save();

                // 创建默认分组
                Group::create([
                    'user_id' => $user->id,
                    'name' => '默认',
                ]);

                // 建立邀请关系
                $user->buildRelationMini($user->id, $request->post('q'));
            }
            // 登录
            $token = JWTAuth::fromUser($user);
            auth('api')->login($user);
            $user = auth('api')->user();
            $login = [
                'user'         => $user,
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('api')->factory()->getTTL() * 60
            ];
            return $this->writeJson(0, $login, '注册成功，页面即将跳转...');
        }
    }
}
